package ca.quicko.webapp.action;

import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.userdetails.UserDetails;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.model.Role;
import org.appfuse.model.User;
import org.appfuse.webapp.action.BaseAction;

/**
 * @author <a href="mailto:eric.s.landry@gmail.com">Eric S. Landry</a>
 *
 */
public class MyBaseAction extends BaseAction {
	private static final long serialVersionUID = -8947164365481629036L;

	private Log log = LogFactory.getLog(getClass());

	/**
	 * @return the userName as string from the logged in user.
	 */
	public String getLoggedInUserName() {
		SecurityContext context = SecurityContextHolder.getContext();

		if (context != null) {
			Authentication auth = context.getAuthentication();

			if (auth != null) {
				Object obj = auth.getPrincipal();
				log.debug("object:" + obj);

				if (obj != null) {
					if (obj instanceof UserDetails) {
						return ((UserDetails) obj).getUsername();
					}
					else {
						return (String) obj;
					}
				}
			}
		}

		return null;
	}

	/**
	 * @return the logged in user
	 */
	public User getLoggedInUser() {
		String userName = getLoggedInUserName();

		if (userName == null) {
			log.warn("userName is null");
			return null;
		}

		log.debug("getting user:" + userName);

		if (userManager == null) {
			return null;
		}

		return userManager.getUserByUsername(userName);
	}

	/**
	 * checks if the logged in user has the role provided.
	 * @param roleName
	 * @return
	 */
	public boolean loggedInUserHasRole(String roleName) {
		if (roleName == null || roleName.length() == 0 || getLoggedInUser() == null) {
			log.warn("roleName is not set right or there is no user found");
			return false;
		}
		for (Role role : getLoggedInUser().getRoles()) {
			if (roleName.equals(role.getName())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 1 will be true other values will be false.
	 */
	public boolean getValueAsBoolean(String booleanStr) {
		if ("1".equals(booleanStr)) {
			return true;
		}
		return false;
	}

}
